import axios from 'axios'
import { initNimSDK } from './initNimSDK'
import { initChatroomSDK, resetChatroomSDK } from './initChatroomSDK'
import {
  deleteSession,
  setCurrSession,
  resetCurrSession
} from './session'
import { 
  showLoading,
  hideLoading,
  showFullscreenImg,
  hideFullscreenImg 
} from './widgetUi'
import {
  sendMsg,
  sendFileMsg,
  sendMsgReceipt,
  sendRobotMsg,
  revocateMsg,
  getHistoryMsgs,
  resetNoMoreHistoryMsgs,
  continueRobotMsg,
  onMsg
} from './msgs'
import {
  markSysMsgRead,
  resetSysMsgs,
  deleteSysMsgs,
  markCustomSysMsgRead
} from './sysMsgs'
import {searchUsers} from './search'

export default {
  logined({
    commit,
    dispatch
  }, token) {
    return new Promise(function (resolve, reject) {
      axios.defaults.headers.common['Authorization'] = token;
      sessionStorage.setItem('token', token);
      commit('logined', token);
      dispatch('profile').then(() => {
        resolve();
      }).catch(() => {
        reject();
      });
    });
  },

  logout({
    commit
  }) {
    return new Promise(function (resolve, reject) {
      sessionStorage.removeItem('admin');
      sessionStorage.removeItem('commission');
      sessionStorage.removeItem('noCommission');
      sessionStorage.removeItem('hasCommission');
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('config');
      commit('logout');
    });
  },

  profile({
    commit
  }) {
    return new Promise(function (resolve, reject) {
      let doctorInfoCache = JSON.parse(sessionStorage.getItem('doctorInfo'));
      let commissionCache = sessionStorage.getItem('commission');
      let noCommissionCache = sessionStorage.getItem('noCommission');
      let hasCommissionCache = sessionStorage.getItem('hasCommission');

      if (doctorInfoCache) {
        commit('profile', doctorInfoCache);
        commit('commission', commissionCache);
        commit('noCommission', noCommissionCache);
        commit('hasCommission', hasCommissionCache);
      } else {
        axios.get('/doctor/profile').then((response) => {
          if (response.data.code == 200) {
            let doctorInfo = response.data.data.admin;
            let commission = response.data.data.commission;
            let noCommission = response.data.data.noCommission;
            let hasCommission = response.data.data.hasCommission;

            sessionStorage.setItem('doctorInfo', JSON.stringify(doctorInfo));
            sessionStorage.setItem('commission', commission);
            sessionStorage.setItem('noCommission', noCommission);
            sessionStorage.setItem('hasCommission', hasCommission);

            commit('profile', doctorInfo);
            commit('commission', commission);
            commit('noCommission', noCommission);
            commit('hasCommission', hasCommission);
            resolve();
          } else {
            this.$message({
              message: response.data.msg,
              type: 'error'
            });
            reject();
          }
        });
      }
    });
  },

  refreshToken({
    commit
  }, token) {
    return new Promise(function (resolve, reject) {
      axios.defaults.headers.common['Authorization'] = token;
      sessionStorage.setItem('token', token);
      commit('refreshToken', token);
    });
  },

  setIMToken({
    commit
  }, token) {
    return new Promise(function (resolve, reject) {
      sessionStorage.setItem('imToken', token);
      commit('setIMToken', token);
    });
  },

  setUnreadMsg({commit},unreadmsgData){ 
    return new Promise(function (resolve, reject) {
      sessionStorage.setItem('unreadMsg', unreadmsgData);
      commit('setUnreadMsg', unreadmsgData);
      resolve();
    });    
  },

  config({
    commit
  }) {
    return new Promise(function (resolve, reject) {
      let configCache = JSON.parse(sessionStorage.getItem('config'));

      if (configCache) {
        commit('config', configCache);
      } else {
        axios.get('/doctor/config').then((response) => {
          if (response.data.code == 200) {
            let config = response.data.data;
            sessionStorage.setItem('config', JSON.stringify(config));
            commit('config', config);
            resolve();
          } else {
            this.$message({
              message: response.data.msg,
              type: 'error'
            });
            reject();
          }
        });
      }
    });
  },

  commission({
    commit
  }, commission) {
    commit('commission', commission);
  },

  noCommission({
    commit
  }, noCommission) {
    commit('noCommission', noCommission);
  },

  hasCommission({
    commit
  }, hasCommission) {
    commit('hasCommission', hasCommission);
  },

  updateRefreshState({ commit }) {
    commit('updateRefreshState')
  },

  // UI 及页面状态变更
  showLoading,
  hideLoading,
  showFullscreenImg,
  hideFullscreenImg,
  continueRobotMsg,

  // 连接sdk请求，false表示强制重连
  connect(store, obj) {
    connectNim(store, obj)
  },
  // 初始化 重新连接SDK
  initNimSDK,

  // 搜索用户信息
  searchUsers,
  initChatroomSDK,
  resetChatroomSDK,

  deleteSession,
  setCurrSession,
  resetCurrSession,

  onMsg,
  sendMsg,
  sendFileMsg,
  sendMsgReceipt,
  sendRobotMsg,
  revocateMsg,
  getHistoryMsgs,
  resetNoMoreHistoryMsgs,
  continueRobotMsg,

  markSysMsgRead,
  resetSysMsgs,
  deleteSysMsgs,
  markCustomSysMsgRead

}

function connectNim({ state, commit, dispatch }, obj) {
  if(obj){
  let loginInfo = {
    account: obj.account,
    sdktoken: obj.im_token,
  };
  dispatch('initNimSDK', loginInfo);}
}

function msgCome() {
  window.nim.onMsg;
  dispatch('onMsg');
}

